<template>
  <a-drawer
      :title="title"
      :visible="visible"
      :destroyOnClose="true"
      :width="400"
      :body-style="{ paddingBottom: '80px' }"
      @close="onClose"
  >
    <a-form layout="vertical">
      <a-form-item label="公司名称" v-bind="validateInfos.org_branch_id">
        <a-select
            v-model:value="modelRef.org_branch_id"
            :fieldNames="{
            label: 'company',
            value: 'id',
          }"
            :options="companyList"
            placeholder="请选择公司"
            @change="changeCompany"
        />
      </a-form-item>
      <a-form-item label="纳税人识别号" v-bind="validateInfos.taxpayer_number">
        <a-button
            type="link"
            v-if="branchNoTaxpayerNumber"
            @click.stop="editTaxpayerNumber"
        >
          去编辑
        </a-button>
        <a-input
            v-else
            placeholder="选择公司自动带入"
            v-model:value="modelRef.taxpayer_number"
            :disabled="true"
        />
      </a-form-item>
      <a-form-item label="开票地址" v-bind="validateInfos.address">
        <a-input
            placeholder="请输入开票地址"
            v-model:value="modelRef.address"
        />
      </a-form-item>
      <a-form-item label="电话" v-bind="validateInfos.phone">
        <a-input
            placeholder="请输入电话"
            v-model:value="modelRef.phone"
            type="tel"
        />
      </a-form-item>
      <a-form-item v-bind="validateInfos.account_id">
        <template #label>
          <a-row style="width: 320px;" justify="space-between">
            <a-col>
              账户信息
            </a-col>
            <a-col>
              <a @click="addAccount">立即添加</a>
            </a-col>
          </a-row>
        </template>
        <a-select
            v-model:value="modelRef.account_id"
            :options="accountList"
            :fieldNames="{
            label: 'name',
            value: 'account_id',
          }"
            placeholder="请选择账户"
            @change="changeAccount"
        />
      </a-form-item>
      <a-form-item label="开户行" v-bind="validateInfos.bank">
        <a-input
            placeholder="选择账户自动带入"
            :disabled="true"
            v-model:value="modelRef.bank"
        />
      </a-form-item>
      <a-form-item label="银行账号" v-bind="validateInfos.bank_account">
        <a-input
            placeholder="选择账户自动带入"
            v-model:value="modelRef.bank_account"
            :disabled="true"
        />
      </a-form-item>
      <a-form-item label="租客申请开票">
        <a-switch :checkedValue="1"
                  :unCheckedValue="2" v-model:checked="modelRef.owner_invoice"/>
      </a-form-item>
      <a-form-item v-show="modelRef.owner_invoice==1">
        <template #label>
          开票须知
          <a-tooltip>
            <template #title>用于租客端提醒租客提交开票申请后，开取纸质发票所需要的周期</template>
            <QuestionCircleOutlined class="ml-5"/>
          </a-tooltip>
        </template>
        <a-textarea
            style="height: 100px"
            placeholder="开票周期"
            v-model:value="modelRef.invoice_desc"
        />
      </a-form-item>
    </a-form>
    <div class="drawer-footer">
      <a-space>
        <a-button @click.prevent="onClose">取消</a-button>
        <a-button type="primary" @click.prevent="onSubmit">保存</a-button>
      </a-space>
    </div>

    <!--  添加或者编辑账户  -->
    <AccountAdd
        @cancel="handleAccountCancel"
        @success="handleAccountSuccess"
        :visible="editAccountVisible"
        :id="currentAccountId"
    />

    <!--  添加或者编辑公司  -->
    <AddCompany
        :visible="companyVisible"
        :id="companyId"
        @handleCancel="handleCompanyCancel"
        @handleSuccess="handleCompanySuccess"
    />
  </a-drawer>
</template>

<script>
import {computed, defineComponent, reactive, toRaw, watch, toRefs} from "vue";
import {Form, message} from "ant-design-vue";
import request from "../../../../common/utils/request";
import utils from "../../../../common/utils/utils";
import AccountAdd from "@/views/setting/UserAccount/modules/AccountAdd.vue";
import AddCompany from "@/views/setting/CompanyInfo/modules/AddCompany.vue";
import {QuestionCircleOutlined} from '@ant-design/icons-vue'

const useForm = Form.useForm;

export default defineComponent({
  name: "AddSeller",
  components: {
    QuestionCircleOutlined,
    AddCompany,
    AccountAdd,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [String, Number],
      default: 0,
    },
  },
  setup(props, {emit}) {
    /**
     * @description: 标题显示
     */
    const title = computed(() => {
      return props.id ? "编辑售方信息" : "新增售方信息";
    });

    const branchNoTaxpayerNumber = computed(() => {
      return (
          (modelRef.org_branch_id || modelRef.org_branch_id == 0) &&
          !modelRef.taxpayer_number
      );
    });

    const accountList = computed(() => {
      return (
          state.companyList.find((v) => v.id == modelRef.org_branch_id)
              ?.account_info || []
      );
    });

    /**
     * @description: 触发关闭
     */
    const onClose = () => {
      emit("cancel");
    };

    const state = reactive({
      companyList: [],
      currentAccountId: 0,
      editAccountVisible: false,
      companyVisible: false,
      companyId: 0,
    });

    /**
     * @description: 表单字段
     */
    const modelRef = reactive({
      taxpayer_number: "",
      bank: "",
      bank_account: "",
      phone: "",
      address: "",
      org_branch_id: undefined,
      account_id: undefined,
      owner_invoice: 2,
      invoice_desc: "开取纸质发票需7天左右"
    });

    /**
     * @description: 验证规则
     */
    const required = [{required: true, message: "必填项"}];
    const rulesRef = reactive({
      org_branch_id: required,
      taxpayer_number: required,
      bank: required,
      bank_account: required,
      phone: required,
      address: required,
      account_id: required,
    });

    /**
     * @description: 创建表单
     */
    const {resetFields, validate, validateInfos} = useForm(
        modelRef,
        rulesRef
    );

    /**
     * @description: 提交表单
     */
    const onSubmit = () => {
      validate().then(() => {
        const params = {...toRaw(modelRef), needMsg: true};
        const success = (res) => {
          message.success(res.msg), emit("success");
        };
        if (props.id) {
          params.id = props.id;
          request
              .put("/org", "/invoice/sellerEdit", params)
              .then((res) => success(res));
        } else {
          request
              .post("/org", "/invoice/sellerAdd", params)
              .then((res) => success(res));
        }
      });
    };

    /**
     * @description: 获取编辑信息
     */
    const getEditInfo = () => {
      request
          .get("/org", "/invoice/seller", {
            id: props.id,
          })
          .then((res) => {
            const {detail} = res;
            setModelRef({
              taxpayer_number: detail.taxpayer_number,
              bank: detail.bank,
              bank_account: detail.bank_account,
              phone: detail.phone,
              address: detail.address,
              org_branch_id: detail?.org_branch_id,
              account_id: detail?.account_id,
              owner_invoice: detail?.owner_invoice,
              invoice_desc: detail?.invoice_desc,
            });
          });
    };

    const setModelRef = (state) => {
      for (let key in state) {
        modelRef[key] = state[key];
      }
    };

    const getCompanyList = () => {
      return new Promise((resolve) => {
        request.get("/org", "/company/orgAndBranch", {}).then((res) => {
          state.companyList = res?.list || [];
          if (!props.id) {
            // 新增 -- 默认总公司账户
            let systemData = (res?.list || []).find((v) => v.is_system == 1);
            if (systemData) {
              modelRef.org_branch_id = systemData.id;
              modelRef.taxpayer_number = systemData?.taxpayer_number || "";
              modelRef.address = systemData?.address || "";
            }
          }
          resolve();
        });
      });
    };

    const addAccount = () => {
      state.editAccountVisible = true;
    };

    const clearAccount = () => {
      modelRef.account_id = undefined;
      modelRef.bank = "";
      modelRef.bank_account = "";
    };

    const changeCompany = (value, option) => {
      modelRef.taxpayer_number = option?.taxpayer_number || "";
      modelRef.address = option?.address || "";
      clearAccount();
    };

    const changeAccount = (value, option) => {
      modelRef.bank = option?.bank || "";
      modelRef.bank_account = option?.bank_account || "";
    };

    const handleAccountCancel = () => {
      state.currentAccountId = 0;
      state.editAccountVisible = false;
    };

    const handleAccountSuccess = () => {
      handleAccountCancel();
      getCompanyList();
    };

    const handleCompanyCancel = () => {
      state.companyId = 0;
      state.companyVisible = false;
    };

    const handleCompanySuccess = () => {
      handleCompanyCancel();
      getCompanyList().then(() => {
        modelRef.taxpayer_number =
            state.companyList.find((v) => v.id == modelRef.org_branch_id)
                ?.taxpayer_number || "";
      });
    };

    const editTaxpayerNumber = () => {
      state.companyId = modelRef.org_branch_id;
      state.companyVisible = true;
    };

    /**
     * @description: 初始化
     */
    const init = () => {
      getCompanyList();
      if (props.id) {
        getEditInfo();
      }
    };

    watch(
        () => props.visible,
        (val) => {
          if (val) {
            // 打开时初始化数据
            init();
          } else {
            // 关闭时重置数据
            resetFields();
            state.companyList = [];
            state.currentAccountId = 0;
            state.companyId = 0;
          }
        }
    );
    return {
      title,
      modelRef,
      validateInfos,
      resetFields,
      ...toRefs(state),
      branchNoTaxpayerNumber,
      accountList,
      onSubmit,
      onClose,
      addAccount,
      changeCompany,
      changeAccount,
      handleAccountSuccess,
      handleAccountCancel,
      handleCompanyCancel,
      handleCompanySuccess,
      editTaxpayerNumber,
    };
  },
});
</script>

<style lang="less" scoped></style>
